# Sihe Think Tank - Backend Startup Script

# Keep window open even if script fails
$ErrorActionPreference = "Continue"

Write-Host "==================================" -ForegroundColor Cyan
Write-Host "  Sihe Think Tank - Backend" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

# Set console encoding to UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null

# Set Python output encoding to UTF-8
$env:PYTHONIOENCODING = 'utf-8'
$env:PYTHONUTF8 = '1'

Write-Host "[OK] UTF-8 encoding configured" -ForegroundColor Green

# Check and clean port 3301
Write-Host "[CHECK] Checking port 3301..." -ForegroundColor Yellow
$port = 3301
$connections = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue

if ($connections) {
    Write-Host "[WARN] Port 3301 is occupied by multiple processes!" -ForegroundColor Red
    Write-Host "[ACTION] Cleaning up ALL Python processes..." -ForegroundColor Yellow
    
    # Kill all Python processes to ensure clean start
    Get-Process python -ErrorAction SilentlyContinue | ForEach-Object {
        try {
            Stop-Process -Id $_.Id -Force -ErrorAction Stop
            Write-Host "[OK] Terminated Python process (PID: $($_.Id))" -ForegroundColor Green
        } catch {
            Write-Host "[WARN] Could not terminate PID: $($_.Id)" -ForegroundColor Yellow
        }
    }
    
    Write-Host "[WAIT] Waiting for ports to be released..." -ForegroundColor Yellow
    Start-Sleep -Seconds 5
    Write-Host "[OK] All ports should now be available" -ForegroundColor Green
} else {
    Write-Host "[OK] Port 3301 is available" -ForegroundColor Green
}

Write-Host ""

# Get script directory and enter backend directory
$scriptPath = $MyInvocation.MyCommand.Path
$scriptDir = Split-Path -Parent $scriptPath
$backendDir = Join-Path $scriptDir "backend"

Write-Host "[INFO] Backend directory: $backendDir" -ForegroundColor Cyan

# Check if backend directory exists
if (-not (Test-Path $backendDir)) {
    Write-Host "[ERROR] Backend directory not found: $backendDir" -ForegroundColor Red
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

Set-Location -Path $backendDir
Write-Host "[OK] Changed to backend directory" -ForegroundColor Green

# Check if virtual environment exists
if (-not (Test-Path ".\venv\Scripts\Activate.ps1")) {
    Write-Host "[ERROR] Virtual environment not found!" -ForegroundColor Red
    Write-Host "Please run: python -m venv venv" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

# Activate virtual environment
Write-Host "[VENV] Activating Python virtual environment..." -ForegroundColor Cyan
& .\venv\Scripts\Activate.ps1
Write-Host "[OK] Virtual environment activated" -ForegroundColor Green

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "  Starting Backend Service..." -ForegroundColor Green
Write-Host "  Press Ctrl+C to stop" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Green
Write-Host ""

# Start backend service
python -m uvicorn app.main:app --host 0.0.0.0 --port 3301 --reload

# If we get here, the service stopped
Write-Host ""
Write-Host "[INFO] Backend service stopped" -ForegroundColor Yellow
Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
